<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Activity;
use app\common\model\Agreement;
use app\common\model\Application;
use app\common\model\Area;
use app\common\model\AwardCeremony;
use app\common\model\Banner;
use app\common\model\Category;
use app\common\model\Goods;
use app\common\model\Group;
use app\common\model\SignUp;
use app\common\model\Version;
use fast\Random;
use think\captcha\Captcha;
use think\Config;
use think\Exception;
use think\Hook;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init', 'touxiang', 'getAlertText', 'captcha', 'getObtainAgreementList', 'getCustomerServiceInfo', 'getAgreementTypeList', 'getBannerList', 'getBannerTypeList', 'getActivityList', 'getActivityDetail'];
    protected $noNeedRight = '*';
    protected $page = 1;
    protected $pageSize = 10;

    public function _initialize()
    {

        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
        }
        //跨域检测
        check_cors_request();

        if (!isset($_COOKIE['PHPSESSID'])) {
            Config::set('session.id', $this->request->server("HTTP_SID"));
        }
        $this->page = $this->request->param('page/d', 1);
        $this->pageSize = $this->request->param('pageSize/d', 10);
        parent::_initialize();
    }

    /**
     * 加载初始化
     *
     * @ApiParams (name="version", type="string", required=true, description="版本号")
     * @ApiParams (name="lng", type="string", required=true, description="经度")
     * @ApiParams (name="lat", type="string", required=true, description="纬度")
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata' => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata' => $upload,
                'coverdata' => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @ApiParams (name="file", type="File", required=true, description="文件流")
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    /**
     * 验证码
     * @ApiParams (name="id", type="string", required=true, description="要生成验证码的标识")
     * @return \think\Response
     */
    public function captcha($id = "")
    {
        \think\Config::set([
            'captcha' => array_merge(config('captcha'), [
                'fontSize' => 44,
                'imageH' => 150,
                'imageW' => 350,
            ])
        ]);
        $captcha = new Captcha((array)Config::get('captcha'));
        return $captcha->entry($id);
    }

    /**
     * 获取协议类型
     */
    public function getAgreementTypeList()
    {
        try {
            $array = [];
            foreach (config('site.agreement') as $key => $value) {
                $array[$key]['id'] = $key;
                $array[$key]['value'] = $value;
            }
            $this->success('success', array_values($array));
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取协议
     */
    public function getObtainAgreementList()
    {
        try {
            $param = $this->request->get();
            if (empty($param['type_id'])) {
                throw new Exception('缺少协议类型ID');
            }
            $result = Agreement::instance()->field('id, content')->where(['type' => $param['type_id']])->find();
            $this->success('success', $result);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取首页banner布局类型
     */
    public function getBannerTypeList()
    {
        try {
            $array = [];
            foreach (config('site.banner') as $key => $value) {
                $array[$key]['id'] = $key;
                $array[$key]['value'] = $value;
            }
            $this->success('success', array_values($array));
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取首页banner
     */
    public function getBannerList()
    {
        try {
            $param = $this->request->get();
            if (empty($param['type_id'])) {
                throw new Exception('缺少布局位置ID');
            }
            $result = Banner::instance()->field('createtime, updatetime, admin_uid', true)->where(['position_type' => $param['type_id']])->select();
            $this->success('success', $result);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取活动列表
     * @throws
     */
    public function getActivityList()
    {
        try {
            $condition['status'] = 1;
            $list = Activity::instance()
                ->field('id, title, image, video, startdate, endtime, signup_start_date, signup_end_date')
                ->where($condition)
                ->order('weight desc')
                ->paginate($this->pageSize, false, ['page' => $this->page])->each(function (&$value) {
                    $value['user_sign_up'] = collection(Application::instance()
                        ->with(['userHasOne'])
                        ->where(['activity_id' => $value['id']])
                        ->select())
                        ->toArray();
                    $value['joinNumber'] = count($value['user_sign_up']);
                    $value['startdate'] = date('Y/m/d H:i:s', strtotime($value['startdate']));
                    $value['endtime'] = date('Y/m/d H:i:s', strtotime($value['endtime']));
                });
            $this->success('success', ['totalPage' => $list->lastPage(), 'list' => $list->items()]);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取活动详情
     * @throws
     */
    public function getActivityDetail()
    {
        try {
            $param = $this->request->get();
            if (empty($param['id'])) {
                throw new Exception('缺少活动ID');
            }
            $condition['id'] = $param['id'];
            $condition['status'] = 1;
            $response = Activity::instance()
                ->field('createtime, updatetime, admin_uid, punch_number, method', true)
                ->where($condition)
                ->find();
            if (!$response) {
                throw new Exception('未找到当前活动');
            }
            $response = $response->toArray();
            $response['startdate'] = date('Y/m/d H:i:s', strtotime($response['startdate']));
            $response['endtime'] = date('Y/m/d H:i:s', strtotime($response['endtime']));
            // todo 获取产品的分类
            $response['cateList'] = [];
            if (!empty($response['cates_ids'])) {
                if ($cate = Category::all(['id' => ['in', explode(',', $response['cates_ids'])], 'status' => 'normal'])) {
                    foreach ($cate as &$items) {
                        $goodsList = collection(Goods::instance()->field('id, goods_name, goods_images, goods_desc, type, method, is_superposition, punch_number_min, punch_number_max, method_init, ranking_range_min, ranking_range_max, input_params, start_date, end_date')
                            ->where(['status' => 1])
                            ->whereRaw("find_in_set(" . $items['id'] . ", cate_ids)")
                            ->select())->toArray();
                        foreach ($goodsList as &$goodsValue) {
                            $awardCeremony = AwardCeremony::instance()->get(['goods_id' => $goodsValue['id'], 'activity_id' => $param['id'], 'user_id' => $this->auth->id ?? 0]);
                            $goodsValue['is_receive'] = empty($awardCeremony) ? false : true;
                            if (!empty($goodsValue['input_params'])) {
                                $goodsValue['inputParams'] = json_decode($goodsValue['input_params'], true);
                                unset($goodsValue['input_params']);
                            }
                        }
                        $items['goodsList'] = $goodsList;
                    }
                    $response['cateList'] = $cate;
                }
            }
            /*$goodsList = collection(Goods::instance()->field('id, goods_name, goods_images, goods_desc, type, method, is_superposition, punch_number_min, punch_number_max, method_init, ranking_range_min, ranking_range_max, input_params')
               ->where(['id' => ['in', explode(',', $response['goods_ids'])]])
               ->select())->toArray();
           foreach ($goodsList as &$goodsValue) {
               $awardCeremony = AwardCeremony::instance()->get(['goods_id' => $goodsValue['id'], 'activity_id' => $param['id'], 'user_id' => $this->auth->id ?? 0]);
               $goodsValue['is_receive'] = empty($awardCeremony) ? false : true;
               if (!empty($goodsValue['input_params'])) {
                   $goodsValue['inputParams'] = json_decode($goodsValue['input_params'], true)[0];
                   unset($goodsValue['input_params']);
               }
           }
           $response['goodsList'] = $goodsList;*/
            // todo 判断当前登录用户是否参与该活动的报名
            $application = Application::instance()->where(['user_id' => $this->auth->id ?? 0, 'activity_id' => $param['id']])->find();
            $response['is_application'] = empty($application) ? false : true;
            // todo 获取当前登录用户对该活动已经打卡过多少次了
            $whereCondition['user_id'] = $this->auth->id ?? 0;
            $whereCondition['activity_id'] = $param['id'];
            $response['punchNumber'] = SignUp::instance()
                ->where($whereCondition)
                //->whereTime('createtime', 'today')
                ->sum('number');
            // todo 获取今日已修改的打卡次数
            $response['toDayUpdatePunchNumber'] = SignUp::instance()->where($whereCondition)
                ->whereTime('createtime', 'today')
                ->order('createtime', 'desc')
                ->value('save_number') ?? 0;
            $this->success('success', $response);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 参与活动报名
     * @throws
     */
    public function applicationActivity()
    {
        try {
            $params = $this->request->post();
            if (empty($params['activity_id'])) {
                throw new Exception('缺少活动id');
            }
            if (!$activity = Activity::instance()->get(['id' => $params['activity_id'], 'status' => 1])) {
                throw new Exception('活动不存在');
            }
            // todo 判断活动开始时间和活动结束时间
            if (!empty($activity['startdate']) && !empty($activity['endtime'])) {
                if (date('Y-m-d H:i:s') > $activity['endtime']) {
                    throw new Exception('该活动已结束，无法参与报名');
                }
            }
            // todo 查看用户是否设置报名时间，设置了则加入报名时间判断
            if (!empty($activity['signup_start_date']) && !empty($activity['signup_end_date'])) {
                if (date('Y-m-d H:i:s') < $activity['signup_start_date']) {
                    throw new Exception('该活动未到开始报名时间');
                }

                if (date('Y-m-d H:i:s') > $activity['signup_end_date']) {
                    throw new Exception('该活动已过报名时间');
                }
            }
            $condition['activity_id'] = $params['activity_id'];
            $condition['user_id'] = $this->auth->id ?? 0;
            if ($rows = Application::instance()->where($condition)->find()) {
                throw new Exception('您已参与过该活动');
            }
            // todo 避免不在该活动组中人成员组进行报名
            $group_id = array_filter(explode(',', $activity['group_id']));
            if ($group_id) {
                $group_id = array_unique($group_id);
                $group = Group::instance()->all(['id' => ['in', $group_id]]);
                $groupName = empty($group) ? '' : implode('|', array_unique(array_column($group, 'group_name')));
                if (!in_array($this->auth->city_group_id, $group_id)) {
                    throw new Exception('本活动只允许组别为【' . $groupName . '】的相关组别参与报名');
                }
            }
            $response = Application::instance()->add($condition);
            $this->success('success', $response);
        } catch (Exception $exception) {
            $this->error('打卡失败：' . $exception->getMessage());
        }
    }

    /**
     * 处理用户批量头像的问题
     * */
    public function touxiang()
    {
        $user = collection((new \app\common\model\User())->select())->toArray();
        $list = [];
        foreach ($user as $key => $value) {
            $list[$key]['id'] = $value['id'];
            if (preg_match('/https:\/\/puch\.sunshinephp\.cn\//', $value['avatar'])) {
                $newUrl = preg_replace(
                    '/https:\/\/puch\.sunshinephp\.cn\//',
                    'https://puch.cdmiaoji.cn/',
                    $value['avatar']
                );
                $list[$key]['avatar'] = $newUrl;
            }
            if (preg_match('/https:\/\/loan\.sunshinephp\.cn\//', $value['avatar'])) {
                $newUrl = preg_replace(
                    '/https:\/\/loan\.sunshinephp\.cn\//',
                    'https://puch.cdmiaoji.cn/',
                    $value['avatar']
                );
                $list[$key]['avatar'] = $newUrl;
            }
            if (preg_match('/https:\/\/puch\.cdmiaoji\.com\//', $value['avatar'])) {
                $newUrl = preg_replace(
                    '/https:\/\/puch\.cdmiaoji\.com\//',
                    'https://puch.cdmiaoji.cn/',
                    $value['avatar']
                );
                $list[$key]['avatar'] = $newUrl;
            }
        }
        foreach ($list as &$val) {
            if (empty($val['avatar'])) {
                unset($val['id']);
            }
        }
        (new \app\common\model\User())->allowField(true)->saveAll(array_values(array_filter($list)), true);
        $this->success('success');
    }

    /**
     * 获取客服信息
     * */
    public function getCustomerServiceInfo()
    {
        $key = $this->request->get('key');
        if (!$key) {
            $this->error('请输入获取配置的KEY');
        }
        $this->success('success', config('site.' . $key));
    }

    /**
     * 获取提示框文案
     * */
    public function getAlertText()
    {
        $key = $this->request->get('key');
        if (!$key) {
            $this->error('请输入获取配置的KEY');
        }
        $this->success('success', config('site.' . $key));
    }
}
